import json 

from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.core import serializers
from models import Post

class author:
    def __init__(self, username):
        self.username = username
class FakeStuff:
    def __init__(self, id):
        self.title = 'Fake Stuff %s' % id
        self.id = id
        self.author = author("FakeUser")
        self.text = "This is the text of the fake stuff with id %s." % id
        
def index(request):
    #post_titles = [post.title for post in Post.objects.all()]
    MGL = '/u/local/workspace' in __file__
    print __file__, MGL
    fakedPosts = []
    for i in range(5):
        fakedPosts.append( FakeStuff(i) )
    return render_to_response("blog/index.html", {"posts":fakedPosts, "MGL":MGL})

def json_blogposts(request):
    id = int(request.GET.get("post_id"))
    print "searching id:", `id`
    if id:
        if 0:
            p = Post.objects.get(id=id)
        else:
            p = FakeStuff(id)
        div = '<div><div>By '+p.author.username+'</div><div>'+p.text+'</div></div>'
        return HttpResponse(
            json.encoder.encode_basestring(div),
            mimetype="application/json"
        )
    return HttpResponse()

_KI = 0
def json_lazy_tree(request):
    global _KI
    # Build node list as JSON formatted string:
    res = '['
    res += '{ "title": "Node '+`_KI+1`+'", "key": "'+`_KI+1`+'", "isLazy": true },'
    res += '{ "title": "Node '+`_KI+2`+'", "key": "'+`_KI+2`+'", "isLazy": true },'
    res += '{ "title": "Node '+`_KI+3`+'", "key": "'+`_KI+3`+'", "isLazy": true }' # no trailing "," at the last line
    res += ']'
    _KI += 3
    
    # Add support for the JSONP protocol:
    # This means, if the request URL contains an argument '?callback=xxx',
    # wrap the result as 'xxx(result)'
    if request.GET.get("callback"):
        res = argDict["callback"] + "(" + res + ")"

    return HttpResponse(
        res,
            mimetype="application/json"
        )
    return HttpResponse()
        
    ## Make sure, content type is JSON:
    #start_response("200 OK", [("Content-Type", "application/json")])
    #
    ## Return result (the square brackets are Python / WSGI specific):
    #return [ res ]
    
